#include <sys/select.h>
#include <vector>
#include <fcntl.h>

#include "TcpSocket.hpp"

class SelectSvr{
  public:
    SelectSvr(){
      Clear();
    }

    void AddFd(int fd){
      FD_SET(fd, &readfds);
      if(fd > max_fd){
        max_fd = fd;
      }
    }
    
    void RemoveFd(int fd){
      FD_CLR(fd, &readfds);
      while(!FD_ISSET(max_fd, &readfds)){
        --max_fd;
      }
    }

    bool SelectWait(std::vector<TcpSocket>& clis, struct timeval* timeout){
      fd_set tmp = readfds;
      int ret = select(max_fd + 1, &tmp, nullptr, nullptr, timeout);
      if(ret < 0){
        perror("select");
        return false;
      }
      if(ret == 0){
        printf("select timeout\n");
        return false;
      }
      for(int i = 0; i <= max_fd; ++i){
        if(FD_ISSET(i, &tmp)){
          clis.push_back(TcpSocket(i));
        }
      }
      return true;
    }

    void Clear(){
      max_fd = -1;
      FD_ZERO(&readfds);
    }
  private:
    int max_fd;
    fd_set readfds;
};
